package org.example.util.file;

/**
 * @author: ZhangMingmin
 * @since: 2025-04-23 15:31
 * @description:
 */

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class BufferedImageToMultipartFile implements MultipartFile {
    
    private final byte[] imgBytes;
    private final String name;
    private final String contentType;

    public BufferedImageToMultipartFile(BufferedImage image, String name, String contentType) throws IOException {
        this.name = name;
        this.contentType = contentType;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, contentType.split("/")[1], baos);
        this.imgBytes = baos.toByteArray();
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return name;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return imgBytes == null || imgBytes.length == 0;
    }

    @Override
    public long getSize() {
        return imgBytes.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgBytes;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgBytes);
    }

    @Override
    public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
        new java.io.FileOutputStream(dest).write(imgBytes);
    }
}
